package service

import (
	"gligli/cache"
	"gligli/model"
	"gligli/serializer"
)

// UserRegisterService 管理用户注册服务
type UserRegisterService struct {
	Nickname      string `form:"nickname" json:"nickname" binding:"required,min=2,max=30"`
	UserName      string `form:"tel" json:"tel" binding:"required"`
	UUID          string `form:"uuid" json:"uuid"`
	SmsCode       string `form:"smscode" json:"smscode"`
	Password      string `form:"pass" json:"pass" binding:"required,min=8,max=40"`
	PasswordCheck string `form:"checkPass" json:"checkPass" binding:"required,min=8,max=40"`
}

// Valid 验证表单
func (service *UserRegisterService) Valid() *serializer.Response {
	if service.PasswordCheck != service.Password {
		return &serializer.Response{
			Status: 40001,
			Msg:    "两次输入的密码不相同",
		}
	}

	// select count(*) from users where nickname = "gligli"
	count := 0
	model.DB.Model(&model.User{}).Where("nickname = ?", service.Nickname).Count(&count)
	if count > 0 {
		return &serializer.Response{
			Status: 40001,
			Msg:    "昵称被占用",
		}
	}

	count = 0
	model.DB.Model(&model.User{}).Where("user_name = ?", service.UserName).Count(&count)
	if count > 0 {
		return &serializer.Response{
			Status: 40001,
			Msg:    "用户名已经注册",
		}
	}

	smsCode, err := cache.RedisClient.Get(service.UserName + service.UUID).Result()
	if err != nil {
		return &serializer.Response{
			Status: 40001,
			Msg:    "redis连接错误",
		}
	}
	if smsCode != service.SmsCode {
		return &serializer.Response{
			Status: 40001,
			Msg:    "验证码错误",
		}
	}

	return nil
}

// Register 用户注册
func (service *UserRegisterService) Register() serializer.Response {

	// 表单验证
	if err := service.Valid(); err != nil {
		return serializer.Response{
			Data: serializer.User{},
		}
	}

	user := model.User{
		Nickname: service.Nickname,
		UserName: service.UserName,
		Status:   model.Active,
	}

	// 加密密码
	if err := user.SetPassword(service.Password); err != nil {
		return serializer.Response{
			Status: 40002,
			Msg:    "密码加密失败",
		}
	}

	// 创建用户
	if err := model.DB.Create(&user).Error; err != nil {
		return serializer.Response{
			Status: 40002,
			Msg:    "注册失败",
		}
	}

	return serializer.Response{
		Data:serializer.BuildUser(user),
	}
}
